var live={
    order_id:"",
    video:document.getElementById("video"),
    logId:0,    //当前最新操作记录ID
    initStatus:false,
    logList:$(".itemList > ul"),
    init:function(orderId){
        var _t=this;
        var W=$("body").width();
        $("#video").css("height",W/16*10);

        _t.order_id=orderId;

        if(_t.order_id!=0){
            _t.getItem();
        }

        this.signature();   //签字模块初始化

        //加载中
        _t.video.onwaiting=function(){
            $("#live .loading").show();
        }

        //开始播放
        _t.video.onplaying=function(){
            $("#live .loading").hide();
        }

        //加载失败
        _t.video.onerror=function(){
            $("#live .loading").hide();
        }
    },
    chooseVideo:function(t){
        var t=$(t),
            src=t.attr("data-src");
        $("#video").attr("src",src);
        t.addClass("current").siblings().removeClass("current");
        this.video.play();
    },

    //读取日志
    getItem:function(){
        var _t=this;
        $.ajax({
            type:"get",
            dataType:"json",
            url:"/JsApi/getLog.html",
            data:{"order_id":this.order_id,"log_id":this.logId},
            success:function(res){

                if(res.status==1||res.status==0){
                    if(res.status==1){
                        _t.printItem(res.data);
                    }
                    var len=res.data.length;
                    if(res.data[len-1].value_type!=99999){
                        setTimeout(function(){
                            _t.getItem();
                        },2000);
                    }
                }else{
                    showMsgTip(res.info);
                    return false;
                }
            }
        })
    },


    
    //数据输出
    printItem:function(data){
        var html='',
            len=data.length,
            i=0;

        this.logId=data[len-1]['log_id'];   //当前最新记录ID

        for(;i<len;i++){
            if(data[i]['status']!=9999){
                this.printLog(data[i]);
            }
        }
        $("#J_loadLog").remove();
        if(!this.initStatus){
            this.initStatus=true;
        }
    },

    //根据操作ID与值，返回结果
    printLog:function(data){
        var selector="J_actId"+data['action_id'].replace(/\./g,"_")+data['type'],
            li=$("#"+selector),
            className=this.initStatus?"zoomIn animated":"",
            value="",
            em=li.find("em"),
            html="",
            _t=this;


        if(data['value_type']==10000){
            //输出保养所选机油

            if(typeof li[0]=="undefined"){
                $("#J_itemList").append('<li id="'+selector+'"><i>&#xe61d;</i>所选机油<em>正在获取</em></li>');
            }
            if(data['status']==1){
                this.printPriceItem(data['val'],"#"+selector,"init");
            }

        }else if(data['value_type']==99999){
            
            if(data['status']==1){
                var html="<li class='"+className+"'><a href='/mobile/myOrderInfoQBY.html?id="+data['order_id']+"'>服务结束 点击查看订单详情</a></li>";
                em.html("已完成");
                this.getOrderPrice();   //显示支付按钮
            }
            
            html+="<li class='"+className+"'><i>&#xe61d;</i>施工流程<em class='fcBlue'>结束</em></li>";
            
        }else if(data['value_type']==10001){    //签字特殊处理

            if(data['status']==1){
                var arr={0:"进行中",1:"已完成",2:"无"},
                    txt=data['val']==null?"进行中":arr[data['val']];
                em.html(txt);
            }else{
                if(em.html()!="进行中"){
                    html="<li id='"+selector+"' class='"+className+"'><i>&#xe61d;</i>"+data['name']+"<em>进行中</em></li>";
                }else if($("#signature").css("visibility")!="visible"){
                    _t.showSignature(data);     //显示签字面板
                }
            }


        }else if(!this.initStatus&&data['status']==1){
            //已完成的
            html+="<li id='"+selector+"' class='"+className+"'><i>&#xe61d;</i>"+data['name']+getValType(data)+"</li>";

        }else if(data['status']==0){
            //进行中
            if(em.html()=="进行中"){
                return false;
            }
            html="<li id='"+selector+"' class='"+className+"'><i>&#xe61d;</i>"+data['name']+"<em>进行中</em></li>";

        }else if(data['status']==1){
            em.replaceWith(getValType(data));
            return ;
        }

        this.logList.prepend(html);

        //计算操作返回值
        function getValType(data){
            var val="",
                classArr={1:"fcGreen",5:"fcOrange",10:"fcRed"},
                cName=classArr[data['bad_level']];

            if(data['value_type']==1){    
                val="<em class='"+cName+"'>"+data['val']+"</em>";   //输出字串
            }else if(data['value_type']==2){
                //val="<em><img src='"+data['val']+"'></em>";   //输出图片
                val="<em class='"+cName+"'>"+data['val']+"</em>";
            }else if(data['value_type']==3){
                if(data['image']==0){
                    val="<em>无</em>";
                }else{
                    val="<audio controls='controls'>"+
                        "<source src='"+data['image'][0]+"' type='audio/mpeg'>"+
                    "</audio>";
                }
               
            }else if(data['value_type']==4){    
                val="<em class='"+cName+"'>"+data['val']+"</em>";   //输出字串
            }else if(data['value_type']==10002){    //车身全检
                if(data['image']!=0){
                    var json=$.parseJSON(data['val']),
                        len=data['image'].length,
                        tpl=json.length+"处损伤{%s%}",
                        list="",
                        i=0;
                    //输出照片
                    //for(;i<len;i++){
                    //   list+='<img src="'+data['image'][i]+'" />';
                    //}
                    cName="fcRed";
                    val=tpl.replace(/\{%s%\}/,list);
                }else{
                    cName="fcGreen";
                    val="无损伤";
                }
                val="<em class='"+cName+"'>"+val+"</em>";   //输出字串
            }
            return val;
        }
        
    },


    //输出价格相关条目 机油ID，容器DOM选择器，是否初选
    printPriceItem:function(jyId,dom,type){
        var _t=this;
        $.ajax({
            type:"post",
            dataType:"json",
            url:"/mobile/getOrderPeijian/",
            data:{"order_id":_t.order_id,"jyId":jyId},
            success:function(res){
                if(res.status==1){
                    if(type=="init"){
                        $(dom).find("em").remove();
                        var html='<div class="jiyou" id="J_jiyouInfo"><img src="http://app2.haixiuyizhan.com/'+res['data']['logo']+'"><p class="name">'+res['data']['pj_name']+'</p><p class="price"><em class="J_price">￥'+res['data']['pj_csprice']+'</em><span>￥'+res['data']['pj_scprice']+'</span></p></div>';
                        $(dom).append(html).show();

                    }else{
                        var html='<li id="J_actId0_2yj" class=""><i></i>机油价格<em class="fcOrange">￥'+(res['data']['pj_csprice']*res['info'])+'</em><div class="jiyou" id="J_jiyouInfo"><img src="http://app2.haixiuyizhan.com/'+res['data']['logo']+'"><p class="count">×'+res['info']+'</p><p class="name">'+res['data']['pj_name']+' 1L</p><p class="price"><em class="J_price">￥'+res['data']['pj_csprice']+'</em><span>￥'+res['data']['pj_scprice']+'</span></p></div></li>',
                        price="￥"+res['data']['pj_csprice']*res.info;
                        $("#J_actId0_3yj").after(html);
                    }
                    
                }
            }
        })
    },


    getOrderPrice:function(){
        var _t=this;
        $.ajax({
            type:"post",
            dataType:"json",
            url:"/mobile/getOrderPrice/",
            data:{"order_id":_t.order_id},
            success:function(res){
                var data=res['data'];
                if(res.status==1){
                    $("#J_price").children("em").html("￥"+data['all_price']);
                    $("#J_price").children("span").html("￥"+data['total_price']);
                    $(".pay").css("bottom",0);
                }
            }
        })
    },

    //显示签字模块
    showSignature:function(data){
        //记录操作日志ID
        $("#J_signature").val(data['log_id']);

        $("#signature").css("visibility","visible");
        var nowS=window.localStorage["signMin"];
        //console.log(nowS>0||nowS==null||nowS==="NaN");
        if(!nowS>0||nowS==="NaN"){
            window.localStorage["signMin"]=data['time']*1+80;
        }else if(nowS>0){
            //填补调用时间差
            //window.localStorage["signMin"]=nowS*1-2;
        }
        this.countDown($("#signature > h4 > span"));
    },

    //倒计时
    countDown:function (box) {
        var _t=this;
        min=(window.localStorage["signMin"])-(Date.parse(new Date())/1000);
        if (min <= 0) {

            localStorage.removeItem("signMin");
            $("#signature").css("visibility","hidden");
        } else {
            box.html(min+"秒后进入下一流程");
            //window.localStorage["signMin"]=min--;
            setTimeout(function() {
                _t.countDown(box);
            },1000);
        }
    },
    //客户签字相关
    signature:function(){
        var canvasDiv = document.getElementById('canvasDiv');
        var canvas = document.createElement('canvas');
        var canvasWidth = $("body").width();
        var canvasHeight = 200;
        var point = {};
        
        point.notFirst = false;

        canvas.setAttribute('width', canvasWidth);
        canvas.setAttribute('height', canvasHeight);
        canvas.setAttribute('id', 'canvas');
        canvasDiv.appendChild(canvas);

        if (typeof G_vmlCanvasManager != 'undefined') {
            canvas = G_vmlCanvasManager.initElement(canvas);
        }
        var context = canvas.getContext("2d");
        var toTop=document.getElementById("signature").offsetTop+37;
        
        canvas.addEventListener("touchstart", function(e) {
            var mouseX = e.touches[0].pageX - this.offsetLeft;
            var mouseY = e.touches[0].pageY - this.offsetTop;
            paint = true;
            addClick(e.touches[0].clientX - this.offsetLeft, e.touches[0].clientY -toTop);
            redraw();
        });

        
        canvas.addEventListener("touchmove",function(e) {
            if (paint) {
                addClick(e.touches[0].clientX - this.offsetLeft, e.touches[0].clientY- toTop, true);
                redraw();
            }
            e.preventDefault();
        });

        canvas.addEventListener("touchend", function(e) {
            paint = false;
        });

        var clickX = new Array();
        var clickY = new Array();
        var clickDrag = new Array();
        var paint;

        function addClick(x, y, dragging) {
            clickX.push(x);
            clickY.push(y);
            clickDrag.push(dragging);
        }

        function redraw() {
            //canvas.width = canvas.width; // Clears the canvas
            context.strokeStyle = "#df4b26";
            context.lineJoin = "round";
            context.lineWidth = 5;

            while (clickX.length > 0) {
                point.bx = point.x;
                point.by = point.y;
                point.x = clickX.pop();
                point.y = clickY.pop();
                point.drag = clickDrag.pop();
                context.beginPath();
                if (point.drag && point.notFirst) {
                    context.moveTo(point.bx, point.by);
                } else {
                    point.notFirst = true;
                    context.moveTo(point.x - 1, point.y);
                }
                context.lineTo(point.x, point.y);
                context.closePath();
                context.stroke();
            }

        }

        var clear = document.getElementById("J_clear");
        var submit = document.getElementById("J_submit");
        clear.addEventListener("click", function() {
            canvas.width = canvas.width;
        });

        submit.addEventListener("click", function() {
            $.ajax({
                url:"/mobile/signature/",
                type:"post",
                dataType:"json",
                data:{"img":canvas.toDataURL("image/png"),"logId":$("#J_signature").val()},
                success:function(res){
                    if(res.status==1){
                        $("#signature").remove();
                        window.localStorage["signMin"]=null;
                        $("#J_actId9yj").find("em").html("已完成");
                    }
                    showMsgTip(res.info);
                    return false;
                }
            })
        });
    }
}
